# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

import os
from random import random, seed

from bertsum.others.utils import test_rouge


def get_rouge(predictions, targets, temp_dir, random_seed=42):
    """
    function to get the rouge metric for the prediction and the reference.

    Args:
        predictions (list of strings): Predictions to be compared.
        target (list of strings): References
        temp_dir (str): Path where temporary folders are created to host the files
            generated by ROUGE application.
        seed (int, optional): Random seed. Defaults to 42.

    Return:
        dictionary: rouge metric

    """

    def _write_list_to_file(list_items, filename):
        with open(filename, "w") as filehandle:
            # for cnt, line in enumerate(filehandle):
            for item in list_items:
                filehandle.write("%s\n" % item)

    seed(random_seed)
    random_number = random()
    os.makedirs(temp_dir, exist_ok=True)
    candidate_path = os.path.join(temp_dir, "candidate" + str(random_number))
    gold_path = os.path.join(temp_dir, "gold" + str(random_number))
    _write_list_to_file(predictions, candidate_path)
    _write_list_to_file(targets, gold_path)
    rouge = test_rouge(temp_dir, candidate_path, gold_path)
    return rouge
